<?php

namespace app\dao\distributor;

use app\dao\BaseDao;
use app\model\distributor\Distributor;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class DistributorDao extends BaseDao
{
    protected function setModel(): string
    {
        return Distributor::class;
    }

    /**
     * @throws DataNotFoundException
     * @throws \ReflectionException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getList(array $where, int $page = 0, int $limit = 0, string $order = '')
    {
        $query = $this->search($where, false)->order('id desc');
        if (isset($where['distributor_name']) && $where['distributor_name']) {
            $query->where('distributor_name', 'like', '%'. $where['distributor_name'] . '%');
        }
        if (isset($where['add_time']) && count($where['add_time']) && $where['add_time'][0]  != '') {
            $add_time_start = $where['add_time'][0] ?? '';
            $add_time_end = $where['add_time'][1] ?? '';
            $query->where('add_time', '>=', $add_time_start)->where('add_time', '<=', $add_time_end);
        }
        $cloneQuery = clone $query;

        $distributes = $query->when($page != 0 && $limit != 0, function ($query) use ($page, $limit) {
            $query->page($page, $limit);
        })->select()->toArray();

        $list = [];
        foreach ($distributes as $distribute) {
            $distribute['today_order_nums'] =  1;
            $distribute['total_order_nums'] =  1;

            $list[] = $distribute;
        }

        $count = $cloneQuery->count();
        return compact('list', 'count');
    }

    /**
     * @throws DataNotFoundException
     * @throws \ReflectionException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getAuditStatus(array $where, int $page = 0, int $limit = 0, string $order = '')
    {
        $query = $this->search($where, false)->order('id desc');
        if (isset($where['distributor_name']) && $where['distributor_name']) {
            $query->where('distributor_name', 'like', '%'. $where['distributor_name'] . '%');
        }
        if (isset($where['add_time']) && count($where['add_time'])) {
            $add_time_start = $where['add_time'][0] ?? '';
            $add_time_end = $where['add_time'][1] ?? '';
            $query->where('add_time', '>=', $add_time_start)->where('add_time', '<=', $add_time_end);
        }
        $cloneQuery = clone $query;

        $list = $query->when($page != 0 && $limit != 0, function ($query) use ($page, $limit) {
            $query->page($page, $limit);
        })->select()->toArray();

        $count = $cloneQuery->count();
        return compact('list', 'count');
    }


    public function all()
    {
        return $this->search(['status' => 1])->field('id,distributor_name')->select();
    }

}